package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;
import java.util.Vector;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.IndexEntryImpl;
import dk.itu.samd.group2.tagapastry.IndexImpl;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagFactory;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

public class IndexExpansionMsg extends TagapastryMsg {

	public static final short TYPE = 5;
	private static final long serialVersionUID = TYPE;
	private Vector<IndexEntry> entries;
	
	public IndexExpansionMsg(Tag tag, NodeHandle sender, Vector<IndexEntry> entries) {
		super(tag, sender);
		this.entries = entries;
	}
	
	public IndexExpansionMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		int resultsSize = buf.readInt();
		entries = new Vector<IndexEntry>(resultsSize);
		for (int i = 0; i < resultsSize; i++) {
			entries.add(new IndexEntryImpl(buf));
		}
	}

	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);
		boolean indexCreated = false;
		
		if (index == null) {		
			index = new IndexImpl(tag, taga, entries);
			indexCreated = true;
		}
		Tag parentTag = TagFactory.duplicateTagMinusExtension(tag);
		char childExtension = tag.getExtension().charAt(tag.getExtension().length() - 1);
		IndexExpansionConfirmationMsg msg = new IndexExpansionConfirmationMsg(parentTag, taga.getNodeHandle(), indexCreated, childExtension);
		taga.send(msg);
		
	}

	@Override
	public short getType() {
		return TYPE;
	}
	
	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
		buf.writeInt(entries.size());
		for (IndexEntry entry : entries) {
			entry.serialize(buf);
		}
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}
	
	@Override
	public String toString() {
		String str = super.toString();
		str += " }";
		return str;
	}
	
	public int getSize() {
		int size = super.getSize();
		for (IndexEntry ie : entries) {
			size += ie.getSize();
		}
		
		return size;
	}

}
